package cc.kigh.oss.service.impl;

import cc.kigh.oss.entity.UploadResult;
import cc.kigh.oss.enumd.OssEnumd;
import cn.hutool.core.util.URLUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import cc.kigh.common.utils.StringUtils;
import cc.kigh.oss.exception.OssException;
import cc.kigh.oss.properties.OssProperties;
import cc.kigh.oss.service.abstractd.AbstractOssStrategy;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;

/**
 * 腾讯云存储策略
 *
 * @author Lion Li
 */
public class QcloudOssStrategy extends AbstractOssStrategy {

    private COSClient client;

    @Override
    public void init(OssProperties cloudStorageProperties) {
        properties = cloudStorageProperties;
        try {
            COSCredentials credentials = new BasicCOSCredentials(
                properties.getAccessKey(), properties.getSecretKey());
            // 初始化客户端配置
            ClientConfig clientConfig = new ClientConfig();
            // 设置bucket所在的区域，华南：gz 华北：tj 华东：sh
            clientConfig.setRegion(new Region(properties.getRegion()));
            if ("Y".equals(properties.getIsHttps())) {
                clientConfig.setHttpProtocol(HttpProtocol.https);
            } else {
                clientConfig.setHttpProtocol(HttpProtocol.http);
            }
            client = new COSClient(credentials, clientConfig);
            createBucket();
        } catch (Exception e) {
            throw new OssException("腾讯云存储配置错误! 请检查系统配置:[" + e.getMessage() + "]");
        }
    }

    @Override
    public void createBucket() {
        doCreate(properties.getPubBucketName(), false);
        doCreate(properties.getPriBucketName(), true);
    }

    private void doCreate(String bucketName, boolean b) {
        try {
            if (client.doesBucketExist(bucketName)) {
                return;
            }
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            if (b) {
                createBucketRequest.setCannedAcl(CannedAccessControlList.Private);
            } else {

                createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            }
            client.createBucket(createBucketRequest);
        } catch (Exception e) {
            throw new OssException("创建Bucket失败, 请核对腾讯云配置信息:[" + e.getMessage() + "]");
        }
    }

    @Override
    public String getServiceType() {
        return OssEnumd.QCLOUD.getValue();
    }

    @Override
    public cc.kigh.oss.entity.UploadResult upload(byte[] data, String path, String contentType, boolean privateAccess) {
        return upload(new ByteArrayInputStream(data), path, contentType, privateAccess);
    }

    @Override
    public cc.kigh.oss.entity.UploadResult upload(InputStream inputStream, String path, String contentType, boolean privateAccess) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(contentType);
            String bucketName = privateAccess ? properties.getPriBucketName() : properties.getPubBucketName();
            client.putObject(new PutObjectRequest(bucketName, path, inputStream, metadata));
        } catch (Exception e) {
            throw new OssException("上传文件失败，请检查腾讯云配置信息:[" + e.getMessage() + "]");
        }
        return new cc.kigh.oss.entity.UploadResult().setUrl(getEndpointLink() + "/" + path).setFilename(path);
    }


    @Override
    public void delete(String path) {
        path = path.replace(getEndpointLink() + "/", "");
        try {
            client.deleteObject(new DeleteObjectRequest(properties.getPubBucketName(), path));
        } catch (Exception e) {
            throw new OssException("上传文件失败，请检腾讯云查配置信息:[" + e.getMessage() + "]");
        }
    }

    @Override
    public cc.kigh.oss.entity.UploadResult uploadSuffix(byte[] data, String suffix, String contentType, boolean privateAccess) {
        return upload(data, getPath(properties.getPrefix(), suffix), contentType, privateAccess);
    }

    @Override
    public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType, boolean privateAccess) {
        return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType, privateAccess);
    }

    @Override
    public String accessSign(String url) {
        // todo
        GeneratePresignedUrlRequest args = new GeneratePresignedUrlRequest(properties.getPriBucketName(), URLUtil.getPath(url));
        args.setExpiration(new Date(System.currentTimeMillis() + properties.getExpire() * 1000));
        return client.generatePresignedUrl(args).toString();
    }

    @Override
    public String getEndpointLink() {
        String endpoint = properties.getEndpoint();
        StringBuilder sb = new StringBuilder(endpoint);
        if (StringUtils.containsAnyIgnoreCase(endpoint, "http://")) {
            sb.insert(7, properties.getPubBucketName() + ".");
        } else if (StringUtils.containsAnyIgnoreCase(endpoint, "https://")) {
            sb.insert(8, properties.getPubBucketName() + ".");
        } else {
            throw new OssException("Endpoint配置错误");
        }
        return sb.toString();
    }
}
